import { useState } from 'react';

interface DraggedItem<T> {
  index: number;
  item: T;
}

const useDragSort = <T>(items: T[]) => {
  const [draggedItem, setDraggedItem] = useState<DraggedItem<T> | null>(null);
  const [sortedItems, setSortedItems] = useState<T[]>(items);

  const handleDragStart = (e: React.DragEvent, index: number) => {
    setDraggedItem({ index, item: sortedItems[index] });
    e.dataTransfer.effectAllowed = 'move';
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent, index: number) => {
    e.preventDefault();

    if (draggedItem === null) return;

    const newItems = [...sortedItems];
    const draggedItemContent = newItems[draggedItem.index];
    newItems.splice(draggedItem.index, 1);
    newItems.splice(index, 0, draggedItemContent);

    setSortedItems(newItems);
    setDraggedItem(null);
  };

  return {
    sortedItems,
    handleDragStart,
    handleDragOver,
    handleDrop,
  };
};

export default useDragSort;
